package com.acmedcare.framework.exchange.center.core.handler;

import com.acmedcare.framework.exchange.center.core.JmxContainerUtil;
import com.acmedcare.framework.exchange.center.core.exception.PluginNotFoundException;
import com.acmedcare.framework.exchange.center.entity.bean.Task;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public class AgentHandlerProxy implements MethodInterceptor {

  @Override
  public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)
      throws Throwable {

    if (method.getName().equals("invoke")) {
      Task task = (Task) objects[0];
      AgentHandlerMBean agentHandler = JmxContainerUtil.AgentHandlers.get(task.getPluginName());
      if (agentHandler == null) {
        throw new PluginNotFoundException(
            String.format("插件:%s,尚未找到，请确认插件已经正确加载!", task.getPluginName()));
      }
      agentHandler.invoke(task);
    }

    return null;
  }
}
